package com.dabaozhan.modules.wx_app.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dabaozhan.common.exception.RRException;
import com.dabaozhan.common.utils.UploadFile;
import com.dabaozhan.modules.wx_app.base.ResponseDto;
import com.dabaozhan.modules.wx_app.enums.ResponseCodeEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

/**
 * @author houzhong
 * @date 2019-01-23 11:02
 */

@Api(value = "上传方法")
@RestController
@RequestMapping("/wx_app")
public class UploadController {

    private static final Logger LOGGER = LoggerFactory.getLogger(UploadController.class);

    @ApiOperation(value = "公用上传方法")
    @RequestMapping("/uploadFile")
    public String uploadFile(@RequestParam(value = "file", required = false) MultipartFile[] file, HttpServletRequest request) {
        ResponseDto<String> responseDto = new ResponseDto<String>();
        try {
            request.setCharacterEncoding("UTF-8");
            //用户id
            String userId = request.getParameter("userId");
            //图片保存路径
            String pathUrl = request.getSession().getServletContext().getRealPath("/")+ ("fileImage/");

            //图片上传成功
            JSONObject jsonObject = UploadFile.uploadFileImg(file,pathUrl);

            //图片名称
            String targetFileName = jsonObject.getString("targetFileName");

            responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_100);
            responseDto.setResult(targetFileName);
        } catch(RRException re){
            responseDto.setCode(re.getCode());
            responseDto.setMessage(re.getMessage());
        } catch (Exception e) {
            responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_500);
            //记录异常日志
            LOGGER.error("公用上传方法发生异常:",e);
        } finally {
            //记录请求入参和返回日志
            LOGGER.info("公用上传方法发生异常:{}-返回结果:{}", JSON.toJSONString(responseDto));
        }
        return JSON.toJSONString(responseDto);
    }
}
